<script setup lang="ts">
// import type { InputMode } from '@tg/types'
import { useField } from 'vee-validate'
import { computed, ref, watch } from 'vue'
import BaseIcon from './BaseIcon.vue'

interface Option {
  label: string
  value: string | number
  icon?: string
  cur?: string
}

interface Props {
  name: string
  modelValue?: string | number
  placeholder?: string
  required?: boolean
  tipMsg?: string
  label?: string
  options?: Option[]
  searchable?: boolean
  closeOnSelect?: boolean
}

defineOptions({
  name: 'BaseSelect',
})

const props = withDefaults(defineProps<Props>(), {
  name: '',
  label: '',
  options: () => [],
  searchable: false,
  closeOnSelect: true
})

const emits = defineEmits(['update:modelValue', 'change'])

const {
  value: inputValue,
  handleBlur,
  handleChange,
} = useField(props.name, undefined, {
  initialValue: props.modelValue,
})

const isShowTip = ref(false)
const inputRef = useTemplateRef<HTMLInputElement | null>('inputRef')
const searchText = ref('')
const showDropdown = ref(false)

function onFocus() {
  active.value = true
}

function onInput(e: Event) {
  handleChange(e)
  emits('update:modelValue', (e.target as HTMLInputElement)?.value)
  emits('change', e)
}

const active = ref(false)

watch(inputValue, (v) => {
  if (v && props.tipMsg) {
    isShowTip.value = false
  }
  if (v === '' && props.tipMsg) {
    isShowTip.value = true
  }
})

function selectItem(item: Option) {
  emits('update:modelValue', item.value)
  emits('change', item.value)
  if (props.closeOnSelect) {
    showDropdown.value = false
  }
  searchText.value = ''
}

function toggleDropdown() {
  showDropdown.value = !showDropdown.value
  if (showDropdown.value) {
    searchText.value = ''
  }
}

// 关闭下拉框
function closeDropdown() {
  showDropdown.value = false
}

// 筛选选项
const filteredOptions = computed(() => {
  if (!props.searchable || !searchText.value) {
    return props.options
  }
  return props.options.filter(option =>
    option.label.toLowerCase().includes(searchText.value.toLowerCase())
  )
})

// 获取当前选中选项的标签
const selectedLabel = computed(() => {
  const selectedOption = props.options.find(option => option.value === inputValue.value)
  return selectedOption ? selectedOption.label : props.placeholder || props.name
})

// 点击外部关闭下拉框
function handleClickOutside(event: MouseEvent) {
  const selectEl = document.querySelector('.base-select')
  if (selectEl && !selectEl.contains(event.target as Node)) {
    closeDropdown()
  }
}

// 添加和移除点击外部关闭的事件监听
watch(showDropdown, (newVal) => {
  if (newVal) {
    setTimeout(() => {
      document.addEventListener('click', handleClickOutside)
    }, 0)
  } else {
    document.removeEventListener('click', handleClickOutside)
  }
})
</script>

<template>
  <BaseTooltip :text="tipMsg" :show="!!tipMsg && isShowTip">
    <div v-if="props.label" class="mb-[.375rem] text-text-white-2 font-[700]">
      {{ props.label }} <span v-if="required" class="text-function-red">*</span>
    </div>
    <div class="base-select relative">
      <button type="button" class="base-input w-full bg-bg-black-1 pr-[.125rem] relative focus:border focus:border-brand"
        @click.stop="toggleDropdown">
        <slot name="left-icon">
          <div v-if="inputValue && props.options.find(o => o.value === inputValue && o.cur)" class="flex items-center">
            <BaseCurrencyIcon v-if="props.options.find(o => o.value === inputValue)?.cur"
              :cur="props.options.find(o => o.value === inputValue)?.cur" style="width: 14px; height: 14px" />
          </div>
        </slot>
        <div class="flex-1 text-left">{{ selectedLabel }}</div>
        <div class="size-[1.25rem] bg-bg-black-4 rounded-[.25rem] flex justify-center items-center">
          <BaseIcon name="uni-arrow-down" />
        </div>
      </button>

      <!-- 下拉框 -->
      <div v-if="showDropdown" class="select-dropdown">
        <!-- 搜索框 -->
        <div v-if="searchable" class="search-container">
          <input v-model="searchText" type="text" class="search-input" placeholder="搜索" @click.stop />
        </div>

        <!-- 选项列表 -->
        <div class="options-container">
          <div v-for="(option, index) in filteredOptions" :key="index" class="option-item"
            :class="{ 'option-selected': option.value === inputValue }" @click="selectItem(option)">
            <div class="option-icon" v-if="option.cur">
              <BaseCurrencyIcon :cur="option.cur" class="size-[.875rem]" />
            </div>
            <div class="option-label">{{ option.label }}</div>
            <div class="option-selected-indicator" :class="{ 'active': option.value === inputValue }"></div>
          </div>
        </div>
      </div>
    </div>
  </BaseTooltip>
</template>

<style scoped lang="scss">
.base-input {
  height: 2.5rem;
  display: flex;
  align-items: center;
  border-radius: 0.5rem;
  border: .0625rem solid var(--color-bg-black-5);
  padding-left: 0.75rem;
  padding-right: 0.5rem;
  gap: 0.5rem;
  transition: all 0.35s cubic-bezier(0.36, 0.66, 0.04, 1);
  color: var(--color-text-white-1);

  &:focus-within {
    border-color: var(--color-brand);
  }

  >input {
    flex: 1;
  }
}

.select-dropdown {
  position: absolute;
  width: 100%;
  background-color: #232626;
  border-radius: 8px;
  box-shadow: 0 .25rem .625rem rgba(0, 0, 0, 0.2);
  margin-top: .25rem;
  z-index: 1000;
  overflow: hidden;
}

.search-container {
  padding: .75rem;
  border-bottom: .0625rem solid #3A4142;
}

.search-input {
  width: 100%;
  height: 2.5rem;
  background-color: #323738;
  border: none;
  border-radius: .375rem;
  padding: 0 .75rem;
  color: #fff;
  font-size: .875rem;

  &::placeholder {
    color: #7A8283;
  }
}

.options-container {
  max-height: 18.75rem;
  overflow-y: auto;
  padding: .5rem 0;
}

.option-item {
  display: flex;
  align-items: center;
  padding: .625rem .75rem;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover {
    background-color: #323738;
  }
}

.option-icon {
  margin-right: .75rem;
}

.option-label {
  flex: 1;
  color: #fff;
  font-size: .875rem;
}

.option-selected {
  background-color: #2c3333;
}

.option-selected-indicator {
  width: 1.25rem;
  height: 1.25rem;
  border-radius: 50%;
  border: .125rem solid #3A4142;
  display: flex;
  align-items: center;
  justify-content: center;

  &.active {
    border-color: #24EE89;
    background-color: #24EE89;

    &::after {
      content: '';
      display: block;
      width: .5rem;
      height: .5rem;
      background-color: #fff;
      border-radius: 50%;
    }
  }
}
</style>
